package com.lotustong.im4d.ipmsg.swt;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.eclipse.swt.SWT;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.events.SelectionListener;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.layout.RowLayout;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.FileDialog;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.MessageBox;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.swt.widgets.Text;

import com.lotustong.im4d.util.Constants;
import com.lotustong.im4d.util.FileItemVO;

/**
 *  
 * 
 * @author Naoki Takezoe
 */
public class ReceiveDialog {
    
    private Button open;
    private Text   text;
    private Shell  shell;
    private Composite composite;
    private Button response;
    private Button close;
    
    private String userName;
    //private String groupName;
    private String host;
    private String message;
    private boolean lock;
    private String date;
    private Messenger messenger;
    
	/**
	 * Constructor for ReceiveDialog.
	 * @param arg0
	 */
	public ReceiveDialog(Shell shell,String userName,String host,
                         String message,boolean lock,Messenger messenger) {
        this.shell = new Shell(shell,SWT.TITLE|SWT.RESIZE|SWT.MIN|SWT.CLOSE);
        this.userName  = userName;
        //this.groupName = groupName;
        this.host      = host;
        this.message   = message;
        this.lock      = lock;
        this.date      = new Date().toString();
        this.messenger = messenger;
        initComponents();
	}
    
    /**
     *  
     */
    private void initComponents(){
        this.shell.setText("Receive Info + ");
        GridLayout layout = new GridLayout();
        this.shell.setLayout(layout);
        
        Label label = new Label(shell,SWT.CENTER);
        label.setText(userName+"("+host+")\n"+date);
        GridData gridData1 = new GridData(GridData.FILL_HORIZONTAL);
        label.setLayoutData(gridData1);
        
        composite = new Composite(shell,SWT.NULL);
        composite.setLayoutData(new GridData(GridData.FILL_BOTH));
        composite.setLayout(new GridLayout());
        
        if(lock){
            this.open = new Button(composite,SWT.NULL);
            //TODO://receive info(Big button)
            this.open.setText("Info");
            GridData gridData2 = new GridData(GridData.FILL_BOTH);
            this.open.setLayoutData(gridData2);
            this.open.addSelectionListener(new OpenListener());
            this.shell.setDefaultButton(this.open);
        } else {
            this.text = new Text(composite,SWT.WRAP|SWT.MULTI|SWT.V_SCROLL|SWT.READ_ONLY|SWT.BORDER);
            this.text.setText(message);
            GridData gridData3 = new GridData(GridData.FILL_BOTH);
            this.text.setLayoutData(gridData3);
        }
        
        Composite buttons = new Composite(shell,SWT.NULL);
        buttons.setLayout(new RowLayout());
        buttons.setLayoutData(new GridData(GridData.HORIZONTAL_ALIGN_CENTER));
        
        close = new Button(buttons,SWT.NULL);
        close.setText(" Close ");
        close.addSelectionListener(new CloseListener());
        
        response = new Button(buttons,SWT.NULL);
        response.setText(" Reply ");
        response.addSelectionListener(new ResponseListener());
        
        Button bt_file = new Button(shell,SWT.NULL);
        bt_file.setText("Attach");
        bt_file.addSelectionListener(new ReceiveAttachListener());
        shell.setSize(500,400);
    }
    
    /**
     * 
     */
    class OpenListener extends SelectionAdapter {
        public void widgetSelected(SelectionEvent e){
            open.dispose();
            text = new Text(composite,SWT.MULTI|SWT.V_SCROLL|SWT.READ_ONLY|SWT.BORDER);
            text.setText(message);
            GridData gridData3 = new GridData(GridData.FILL_BOTH);
            text.setLayoutData(gridData3);
            composite.layout();
            
            //  
            try {
                messenger.readMsg(host);
            } catch(IOException ex){
                //  
                ex.printStackTrace();
                MessageBox mesBox = new MessageBox(shell,SWT.OK|SWT.ICON_ERROR);
                mesBox.setText("info");
                mesBox.setMessage(ex.toString());
                mesBox.open();
            }
        }
    }
    /**
     * Class:ReceiveAttachListener
     */
    public class ReceiveAttachListener implements SelectionListener {

    	public void widgetDefaultSelected(SelectionEvent e) {
    	}

    	public void widgetSelected(SelectionEvent e) {
    		// TODO tz:receive attach
    		String str = message;
    		String allFile = message.substring(message.indexOf(Constants.FILE_BEIGN_MARK)+Constants.FILE_BEIGN_MARK.length());
    		String[] fileListStr = allFile.split(Constants.FILE_SEPARATER_LIST_MARK);
    		List<FileItemVO> fileList = new ArrayList<FileItemVO>();
    		for(int i=0;i<fileListStr.length;i++){
    			if(fileListStr[i].trim()!=""){
    				String[] fileStr = fileListStr[i].split(Constants.FILE_SEPARATER_FILE_MARK);
    				FileItemVO vo =new FileItemVO(fileStr[0],fileStr[1]);
    				fileList.add(vo);
    			}
    		}
    		
    		
    		FileDialog dialog = new FileDialog (shell, SWT.SAVE);
//    		dialog.setFilterNames (new String [] {"Batch Files", "All Files (*.*)"});
//    		dialog.setFilterExtensions (new String [] {"*.bat", "*.*"}); //Windows wild cards
    		dialog.setFilterPath ("c:\\"); //Windows path
    		dialog.setFileName (fileList.get(0).getName());
    		dialog.setText("aaaaaa---aaa");
//    		System.out.println ("Save to: " + dialog.open ());
    		{
    			String res = (String) dialog.open();
    			BufferedOutputStream out = null;
    		    if (res != null) {
    		        try {
						out = new BufferedOutputStream(new FileOutputStream(new File(res)));
	    		        byte[] buffer = new byte[8192];
	    		        buffer = fileList.get(0).getContent().getBytes();
//	    		        int count=buffer.length;
						out.write(buffer);
	    		        out.flush();
					} catch (FileNotFoundException e1) {
						// TODO Auto-generated catch block
						e1.printStackTrace();
					}catch (IOException e1) {
						// TODO Auto-generated catch block
						e1.printStackTrace();
					}


    		    }
    		}
    	}

    }
    /**
     *  
     */
    class CloseListener extends SelectionAdapter {
        public void widgetSelected(SelectionEvent e){
            shell.dispose();
        }
    }
    
    /**
     *  
     */
    class ResponseListener extends SelectionAdapter {
        public void widgetSelected(SelectionEvent e){
            String msg = message;
            if(lock && text==null){
                msg = "";
            }
            SendDialog dialog = new SendDialog(shell,host,userName,msg,messenger);
            dialog.open();
        }
    }
    
    /**
     *  
     */
    public void open(){
        Display display = this.shell.getDisplay();
        this.shell.open();
        
        // 
        while (!this.shell.isDisposed ()){
            if (!display.readAndDispatch ()){
                display.sleep ();
            }
        }
    }
    
    /**
     *  
     */
    public static void main(String[] args){
        Display display = new Display();
        Shell shell = new Shell(display);
        ReceiveDialog dialog = new ReceiveDialog(shell,"takezoe","TMS2","test",true,null);
        dialog.open();
    }

}
